import base_routers from "../base_routers";

export default async (ctx, next) => {

    if (ctx.request.body.keyword) {
        ctx.request.body[base_routers.Op.or] = {
            title: {
                [base_routers.Op.regexp]: ctx.request.body.keyword
            },
            description: {
                [base_routers.Op.regexp]: ctx.request.body.keyword
            },

        }
    }
    delete ctx.request.body.keyword;
    const video = base_routers.model.video.findAndCountAll({
        where: ctx.request.body,
        include: [
            {
                model: base_routers.model.user,
                attributes: {
                    exclude: ['email', 'phoneNumber', 'trueName', 'password']
                }
            }
        ]
    });
    const user_payment_history = base_routers.model.payment_history.findAll({
        where: {
            userId: ctx.state.user.id,
            type: "video",
            status: "1"
        }
    });
    ctx.clientData = Promise.all([video, user_payment_history])
        .then(([_video, _user_payment_history]) => {
            let _video_rows = _video.rows;
            for (let i = 0, len = _video_rows.length; i < len; i++) {
                if (_user_payment_history.length === 0 && _video_rows[i].dataValues.current_price > 0) {
                    _video_rows[i].src = "请购买本视频"
                } else if (_user_payment_history.length !== 0 && _video_rows[i].dataValues.current_price > 0) {
                    for (let i2 = 0, len2 = _user_payment_history.length; i2 < len2; i2++) {
                        if (_user_payment_history[i] && _user_payment_history[i].dataValues.videoId === _video_rows[i].id) {
                            _video_rows[i].src = "请购买本视频"
                        }
                    }
                }
            }
            _video.rows = _video_rows;
            return _video
        });
    await next();
}